package com.cbw.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cbw.blog.ResponseData.StaticticsBo;
import com.cbw.blog.entity.Article;
import com.cbw.blog.entity.Comment;
import com.cbw.blog.entity.Statistic;
import com.cbw.blog.mapper.ArticleMapper;
import com.cbw.blog.mapper.CommentMapper;
import com.cbw.blog.mapper.StatisticMapper;
import com.cbw.blog.service.ISiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SiteServiceImpl implements ISiteService {
    @Resource
    CommentMapper commentMapper;

    @Resource
    ArticleMapper articleMapper;
    @Resource
    StatisticMapper statisticMapper;



    @Override
    public Page<Comment> recentComments(int count) {

        Page<Comment> commentPage = new Page<>(1, count > 10 || count < 1 ? 10 : count);
        return  commentMapper.selectPage(commentPage, null);

    }

    @Override
    public Page<Article> recentArticles(int count) {
        Page<Article> articlePage = new Page<>(1, count > 10 || count < 1 ? 10 : count);
        Page<Article> selectPage = articleMapper.selectPage(articlePage, null);
        List<Article> records = selectPage.getRecords();

        List<Article> list = records.stream().map(item -> {
            Statistic statistic = statisticMapper.selectOne(new QueryWrapper<Statistic>().eq("article_id", item.getId()));
            item.setHits(statistic.getHits());
            item.setCommentsNum(statistic.getCommentsNum());
            return item;
        }).collect(Collectors.toList());
        selectPage.setRecords(list);
        return selectPage;
    }

    @Override
    public StaticticsBo getStatistics() {
        Integer articles= articleMapper.selectCount(null).intValue();
        Integer comments = commentMapper.selectCount(null).intValue();

        StaticticsBo staticticsBo = new StaticticsBo();
        staticticsBo.setArticles(articles);
        staticticsBo.setComments(comments);

        return staticticsBo;
    }

    @Override
    public void updateStatistics(Article article) {
        Statistic statistic = statisticMapper.selectOne(new QueryWrapper<Statistic>().eq("article_id", article.getId()));
        statistic.setHits(statistic.getHits()+1);
        statisticMapper.updateById(statistic);
    }
}
